﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Pavilion
{
    public class NodeScript
    {
        public event NameChangedDelegate NameChanged;

        public string Name { get { return name; } set { SetName(value); } }
        public NodeScriptType NodeScriptType { get; set; }
        public ContainerNode RootContainer { get; private set; }

        private string name;

        public NodeScript(string name, NodeScriptType nodeScriptType = NodeScriptType.Mix)
        {
            this.Name = name;
            this.NodeScriptType = nodeScriptType;
            this.RootContainer = new ContainerNode("Root");
        }

        public void LoadScript(string nodeScriptPath, string resourceName)
        {
            ScriptXmlSerializer scriptXmlSerializer = new ScriptXmlSerializer();

            XElement rootScriptXElement = XDocument.Load(nodeScriptPath + Name + ".xml").Element("Script");
            NodeScriptType = GameEngine.ParseObject<NodeScriptType>(rootScriptXElement.Attribute("Type").Value);

            RootContainer = scriptXmlSerializer.DeserializeContainerNode(rootScriptXElement.Element("ContainerNode"), resourceName);
        }

        private void SetName(string value)
        {
            if (name == value)
                return;

            string oldName = name;
            name = value;

            OnNameChanged(oldName, name);
        }

        private void OnNameChanged(string oldName, string newName)
        {
            if (NameChanged != null)
                NameChanged(oldName, newName);
        }
    }

    public enum NodeScriptType
    {
        Animation,
        Music,
        Sound,
        Behavior,
        Mix
    }
}
